package allrobots.DispensingMachineThread;

import allrobots.DispensingMachine.DMAndRobotOosOis;
import allrobots.DispensingMachine.DMAndRobotSocket;
import allrobots.DispensingMachine.DMOosAndOis;
import allrobots.RobotThread.RegularReplies;
import t10086.Data.Robot.RobotInfo;
import t10086.Model.Messages.Message;
import t10086.Model.Messages.MessageType;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Map;

public class DMFinishToSystem implements Runnable {
    public static boolean connectionStateRobot = false;
    private final ObjectOutputStream oos = DMOosAndOis.oos;
    private final ObjectInputStream ois = DMOosAndOis.ois;
    private ObjectOutputStream oosRobot;
    private ObjectInputStream oisRobot;

    @Override
    public void run() {
        //向主系统发送信息请求机器人(完成)；
        Message toSystemMessage = new Message(MessageType.REST_ROBOT_REQUEST,null);
        //发送者
        toSystemMessage.setSender((InetSocketAddress) DMOosAndOis.socket.getLocalSocketAddress());
//            System.out.println(socket.getLocalSocketAddress());
        //接收者
        toSystemMessage.setReceiver((InetSocketAddress) DMOosAndOis.socket.getRemoteSocketAddress());
//            System.out.println(socket.getRemoteSocketAddress());
        System.out.println("发起空闲机器人请求");
        try {
            oos.writeObject(toSystemMessage);
            oos.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //收到系统信息得到ip和地址，等待系统响应；
        try {
            Object fromSystem = null;
            while (fromSystem == null) {
                fromSystem = ois.readObject();
                if (fromSystem != null) {
                    Message messageFromSystem = (Message) fromSystem;
                    //取得ip和端口号（完成）;
                    Map<String,Object> responseMap = messageFromSystem.convertData(Map.class);
                    System.out.println("收到空闲列表");
                    LinkedList<RobotInfo>freeRobots = (LinkedList<RobotInfo>) responseMap.get("robotList");
                    RobotInfo freeRobot=freeRobots.get(0);
                    //连接机器人(完成)
                    System.out.println(freeRobot.getListenedAddress());
                    connectRobot(freeRobot.getListenedAddress(),freeRobot.getSerialNumber());
                    //给机器人发送信息让机器人
                    Message toRobotMessage = new Message(MessageType.DISPENSING_MESSAGE,"recipe");
                    oosRobot.writeObject(toRobotMessage);
                    oosRobot.flush();
                    //调用剩下线程完成接下来的任务；
                    new Thread(new DMFinishToRobotThread(ois, oos,oisRobot,oosRobot,freeRobot.getSerialNumber())).start();
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private void connectRobot(InetSocketAddress inetSocketAddress,String number) {
        try {

            Socket socket = new Socket();
            socket.connect(inetSocketAddress);
//            System.out.println(robotAddress+" "+port);
            oosRobot = new ObjectOutputStream(socket.getOutputStream());
            oisRobot = new ObjectInputStream(socket.getInputStream());
            connectionStateRobot = true;
            System.out.println("PharmacistThread Connect System Success");
        } catch (Exception e) {
            e.printStackTrace();
            connectionStateRobot = false;
        }
    }
}
